package com.example.demo01.i18n;

import com.example.demo01.config.DefaultLanguageConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Locale;

/**
 * @author wangxun
 * 必须将其 BeanName 定义为 "localeResolver"
 */
@Slf4j
@Component("localeResolver")
public class DefaultLocaleResolver implements LocaleResolver {

    @Autowired
    private DefaultLanguageConfig deployConfig;


    @Override
    public Locale resolveLocale(HttpServletRequest request) {
        String lang = request.getHeader("lang");
        log.info("传入的Lang参数信息------------>【{}】", lang);
        Locale locale = Locale.getDefault();
        String[] language = null;
        String langDefaultCode = this.deployConfig.getLangDefaultCode();
        if (StringUtils.isNotBlank(lang)) {
            language = lang.split("_");
        } else if (StringUtils.isNotBlank(langDefaultCode)) {
            language = langDefaultCode.split("_");
        }

        HttpSession session;
        if (language != null) {
            locale = new Locale(language[0], language[1]);
            session = request.getSession();
            session.setAttribute("lang_session", locale);
        } else {
            session = request.getSession();
            Locale localeInSession = (Locale) session.getAttribute("lang_session");
            if (localeInSession != null) {
                locale = localeInSession;
            }
        }

        return locale;
    }

    @Override
    public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {

    }
}
